package com.fingard.dsp.bank.directbank.scb02;

import org.apache.commons.lang.StringUtils;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.directbank.chinapay01.util.LogUtil;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.dsp.bank.reqrespobj.single.detail.ReqPayRecDetail;
import com.fingard.io.FileHelper;
import com.fingard.text.Base64Helper;
import com.fingard.text.StringHelper;

import java.io.*;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.text.Normalizer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author XueJy on 2018/8/2.
 * @version 1.0
 */
public class SCB02Base extends DirectBase {
    //汉字Regex
    static Pattern pattern = Pattern.compile("[\\u4E00-\\u9FA5]");
    static SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

    protected String getCharset() {
        return getBankConfig().getCharset("UTF-8");
    }


    //获取文件夹目录下所有文件名
    List<String> getDirectoryAllFileName(String balanceFilePath) {
        List<String> fileNames = new ArrayList<String>();
        File file = new File(balanceFilePath);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                fileNames.add(files[i].getName());
            }
        }
        return fileNames;
    }


    //获取文件夹目录下所有文件名
    List<String> getDirChildNameByDate(String balanceFilePath) {
        List<String> fileNames = new ArrayList<String>();
        File file = new File(balanceFilePath);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            Arrays.sort(files, new Comparator<File>() {
                @Override
                public int compare(File f1, File f2) {
                    //GCNA5011.PAYMENTS.20190213095144VZ.QLPAY012R.5306.CSV-BANSTA.rpt
                    long dateln1 = f1.lastModified();
                    long dateln2 = f2.lastModified();
                    String[] date1 = f1.getName().split("\\.");
                    if (date1.length > 3) {
                        try {
                            dateln1 = Format.DateTime14Format.parse(date1[2].substring(0, 14)).getTime();
                        } catch (Exception ignored) {
                        }
                    }
                    String[] date2 = f2.getName().split("\\.");
                    if (date2.length > 3) {
                        try {
                            dateln2 = Format.DateTime14Format.parse(date2[2].substring(0, 14)).getTime();
                        } catch (Exception ignored) {
                        }
                    }
                    long diff = dateln1 - dateln2;
                    if (diff > 0) {
                        return -1;
                    } else if (diff == 0) {
                        return 0;
                    } else {
                        return 1;//如果 if 中修改为 返回-1 同时此处修改为返回 1  排序就会是递减
                    }
                }

                @Override
                public boolean equals(Object obj) {
                    return true;
                }
            });

            for (int i = 0; i < files.length; i++) {
                fileNames.add(files[i].getName());
            }
        }
        return fileNames;
    }


    //分割内容并且格式化 "BAL"-->BAL
    String[] splitStringWithComma(String splitStr) {
        String newstr = "";
        List<String> sList = new ArrayList<String>();

        boolean isSplice = false;
        String[] array = splitStr.split(",");
        for (String str : array) {
            if (!StringHelper.isNullOrEmpty(str) && str.indexOf('"') > -1) {
                String firstchar = str.substring(0, 1);
                String lastchar = "";
                if (str.length() > 0) {
                    lastchar = str.substring(str.length() - 1, str.length());
                }
                if (firstchar.equals("\"") && !lastchar.equals("\"")) {
                    isSplice = true;
                }
                if (lastchar.equals("\"")) {
                    if (!isSplice) {
                        newstr += str;
                    } else {
                        newstr = newstr + "," + str;
                    }

                    isSplice = false;
                }
            } else {
                if (StringHelper.isNullOrEmpty(newstr)) {
                    newstr += str;
                }
            }

            if (isSplice) {
                //添加因拆分时丢失的逗号
                if (StringHelper.isNullOrEmpty(newstr)) {
                    newstr += str;
                } else {
                    newstr = newstr + "," + str;
                }
            } else {
                sList.add(newstr.replace("\"", "").trim());//去除字符中的双引号和首尾空格
                newstr = "";
            }
        }
        return sList.toArray(new String[sList.size()]);

    }

    //复制文件
    boolean copyFile(String srcFile, String destPath) {
        boolean flag = false;
        FileInputStream fin = null;
        FileOutputStream fout = null;
        FileChannel fcin = null;
        FileChannel fcout = null;
        File toDir = new File(destPath);
        //不存在目标目录创建目录
        if (!toDir.exists()) {
            if (!toDir.mkdirs()) {
                WriteBankLogLn("拷贝目标目录创建失败");
                return flag;
            }
        }
        File aimFile = new File(srcFile);
        String destFile;
        if (destPath.endsWith("\\")) {
            destFile = getTrimPath(destPath) + File.separator + aimFile.getName();
        } else {
            destFile = getTrimPath(destPath) + File.separator + aimFile.getName();

        }
        if (new File(destFile).exists()) {
            WriteBankLogLn("拷贝文件失败:目标文件已存在");
            return flag;
        }

        try {
            // 获取源文件和目标文件的输入输出流
            fin = new FileInputStream(srcFile);
            fout = new FileOutputStream(destFile);
            // 获取输入输出通道
            fcin = fin.getChannel();
            fcout = fout.getChannel();
            // 创建缓冲区
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            while (true) {
                // clear方法重设缓冲区，使它可以接受读入的数据
                buffer.clear();
                // 从输入通道中将数据读到缓冲区
                int r = fcin.read(buffer);
                // read方法返回读取的字节数，可能为零，如果该通道已到达流的末尾，则返回-1
                if (r == -1) {
                    flag = true;
                    break;
                }
                // flip方法让缓冲区可以将新读入的数据写入另一个通道
                buffer.flip();
                // 从输出通道中将数据写入缓冲区
                fcout.write(buffer);
            }
            fout.flush();
        } catch (IOException e) {
            LogUtil.writeErrorLog("CopyFile fail", e);
        } finally {
            try {
                if (null != fin) {
                    fin.close();
                }
                if (null != fout) {
                    fout.close();
                }
                if (null != fcin) {
                    fcin.close();
                }
                if (null != fcout) {
                    fcout.close();
                }
            } catch (IOException ex) {
                LogUtil.writeErrorLog("Releases any system resources fail", ex);
            }
        }
        return flag;
    }

    //写入文件
    boolean writeFile(String fullFilePath, String fileContent,
                      String encoding) throws IOException {
        File tmpFile = new File(fullFilePath);
        File parentDir = new File(tmpFile.getParent());
        if (!parentDir.exists()) {
            parentDir.mkdirs();
        }
        if (!tmpFile.exists()) {
            tmpFile.createNewFile();
        }
        FileOutputStream fout = null;
        FileChannel fcout = null;
        try {
            fout = new FileOutputStream(fullFilePath);
            // 获取输出通道
            fcout = fout.getChannel();
            // 创建缓冲区
            // ByteBuffer buffer = ByteBuffer.allocate(1024);
            ByteBuffer buffer = ByteBuffer.wrap(fileContent.getBytes(encoding));
            fcout.write(buffer);
            fout.flush();
        } catch (IOException ex) {
            LogUtil.writeErrorLog("WriteFile fail", ex);
            return false;
        } finally {
            try {
                if (null != fout) {
                    fout.close();
                }
                if (null != fcout) {
                    fcout.close();
                }
            } catch (IOException ex) {
                LogUtil.writeErrorLog("Releases any system resources fail", ex);
                return false;
            }
        }
        return true;
    }

    //为字段中的逗号加上双引号
    String hasCommaAddDoubleQuotes(String field) {
        if (!StringHelper.isNullOrEmpty(field)) {
            if (field.indexOf(',') > -1) {
                //字符串中包含字符逗号
                field = '"' + field + '"';
            }
        }
        return field;
    }

    void scb02Download() throws Exception {
        boolean result = false;
        // pay
        String receivePaymentStatusACK3FilePath = getH2HPath("ReceivePaymentStatusACK3FilePath");
        String receivePaymentStatusREJ3FilePath = getH2HPath("ReceivePaymentStatusREJ3FilePath");
        String receivePaymentStatusFilePath = getH2HPath("ReceivePaymentStatusFilePath");
        //payBack
        String payReturnACK3byWINTER = getH2HPath("PayReturnACK3byWINTER");
        String payReturnREJ3byWINTER = getH2HPath("PayReturnREJ3byWINTER");
        String payReturnRPTbyWINTER = getH2HPath("PayReturnRPTbyWINTER");
        //下载付款的ACK3, REJ3，RPT
        folderToFolder(receivePaymentStatusACK3FilePath, payReturnACK3byWINTER);
        folderToFolder(receivePaymentStatusREJ3FilePath, payReturnREJ3byWINTER);
        folderToFolder(receivePaymentStatusFilePath, payReturnRPTbyWINTER);
        // rec
        //D:\Workspaces\FilesForDevelop\BankPort\SCB02\host2host\documents\collections\in\ack3\
        //代收暂时不用
//        String receiveBatRecStatusACK3FilePath = getH2HPath("ReceiveBatRecStatusACK3FilePath");
//        String receiveBatRecStatusREJ3FilePath = getH2HPath("ReceiveBatRecStatusREJ3FilePath");
//        String receiveBatRecStatusFilePath = getH2HPath("ReceiveBatRecStatusFilePath");
//        String recReturnACK3byWINTER = getH2HPath("RecReturnACK3byWINTER");
//        String recReturnREJ3byWINTER = getH2HPath("RecReturnREJ3byWINTER");
//        String recReturnRPTbyWINTER = getH2HPath("RecReturnRPTbyWINTER");
//        folderToFolder(receiveBatRecStatusACK3FilePath, recReturnACK3byWINTER);
//        folderToFolder(receiveBatRecStatusREJ3FilePath, recReturnREJ3byWINTER);
//        folderToFolder(receiveBatRecStatusFilePath, recReturnRPTbyWINTER);
    }

    // 按日期备份文件
    void folderToFolder(String fromPath, String toPath) throws ParseException {
        //读取RPT/REJ3文件夹下所有的文件
        List<String> fileNames = getDirectoryAllFileName(fromPath);
        for (String fileName : fileNames) {
            // 获取文件名称中的日期，并组装成路径名称
            //RPT样板
            //GCN01602.PAYMENTS.20151014135500J6.QLPAY012R.5224.CSV-BANSTA.rpt
            // Rej3 样板
            //GCN01602.PAYMENTS.20151008020602.3802.winterPay0006.csv.rej3
            //GCNA5011.REPORTSCUST.20170402044147P6.QLPAY008R.5278.MT942-UTF8.rpt
            //GCNA6309.PAYMENTS.20191226100425XO.QLPAY020R.4877.INTRACUST.rpt
            String[] filenames = fileName.split("\\.");

            //找出带日期的段历史余额文件存到前一天
            String datePath = "";

            if (filenames.length > 2) {
                datePath = filenames[2];
            } else {
                continue;
            }
            if (filenames.length > 5 && (filenames[5].startsWith("INTRA") || filenames[5].startsWith("MT942") || filenames[5].startsWith("MT940") || filenames[5].startsWith("PRIORCUST"))) {
                Date fileRecDate = Format.Date8Format.parse(datePath.substring(0, 8));
                Calendar fileRecCal = Calendar.getInstance();
                fileRecCal.setTime(fileRecDate);
                // 把所有的历史或者今日都放到对应的日期文件夹下，历史的放在前一天的文件夹下（历史的文件第二天生成）。
                if (filenames[5].startsWith("PRIORCUST")) {
                    fileRecCal.add(Calendar.DAY_OF_MONTH, -1);
                }
                //fileRecCal.add(Calendar.DAY_OF_YEAR, -1);
                datePath = Format.Date8Format.format(fileRecCal.getTime());
            }

            //截取0-7 一共八位日期字段
            String toPath2 = getTrimPath(toPath) + File.separator + datePath.substring(0, 6) + File.separator + datePath.substring(6, 8);
            File toPaths = new File(toPath2);
            if (!toPaths.exists()) {
                toPaths.mkdirs();
            }
            //原文件路径
            String fullName = getTrimPath(fromPath) + File.separator + fileName;

            //拷贝文件 拷贝成功删除原文件
            if (copyFile(fullName, toPath2)) {
                WriteBankLogLn("拷贝文件" + fullName + "至" + toPath2);
                if (!new File(fullName).delete()) {
                    WriteBankLogLn("已备份文件" + fullName + " 删除失败,请手动删除");
                }
            }
        }
    }
    // 不按日期备份文件
    void folderToFolder(String fromPath, String toPath, int temp) throws ParseException {
        //读取RPT/REJ3文件夹下所有的文件
        List<String> fileNames = getDirectoryAllFileName(fromPath);
        for (String fileName : fileNames) {
            String[] filenames = fileName.split("\\.");

            //找出带日期的段历史余额文件存到前一天
            String datePath = "";

            if (filenames.length > 2) {
                datePath = filenames[2];
            } else {
                continue;
            }
            if (filenames.length > 5 && (filenames[5].startsWith("INTRA") || filenames[5].startsWith("MT942") || filenames[5].startsWith("MT940") || filenames[5].startsWith("PRIORCUST"))) {
                Date fileRecDate = Format.Date8Format.parse(datePath.substring(0, 8));
                Calendar fileRecCal = Calendar.getInstance();
                fileRecCal.setTime(fileRecDate);
                // 把所有的历史或者今日都放到对应的日期文件夹下，历史的放在前一天的文件夹下（历史的文件第二天生成）。
                if (filenames[5].startsWith("PRIORCUST")) {
                    fileRecCal.add(Calendar.DAY_OF_MONTH, -1);
                }
                //fileRecCal.add(Calendar.DAY_OF_YEAR, -1);
                datePath = Format.Date8Format.format(fileRecCal.getTime());
            }

            //截取0-7 一共八位日期字段
            String toPath2 = getTrimPath(toPath);
            File toPaths = new File(toPath2);
            if (!toPaths.exists()) {
                toPaths.mkdirs();
            }
            //原文件路径
            String fullName = getTrimPath(fromPath) + File.separator + fileName;

            //拷贝文件 拷贝成功删除原文件
            if (copyFile(fullName, toPath2)) {
                WriteBankLogLn("拷贝文件" + fullName + "至" + toPath2);
                if (!new File(fullName).delete()) {
                    WriteBankLogLn("已备份文件" + fullName + " 删除失败,请手动删除");
                }
            }
        }
    }

    // 按日期备份文件 flag针对加强型MT
    void folderToFolder(String fromPath, String toPath, String flag) throws ParseException {
        //读取RPT/REJ3文件夹下所有的文件
        List<String> fileNames = getDirectoryAllFileName(fromPath);
        for (String fileName : fileNames) {
            // 获取文件名称中的日期，并组装成路径名称
            //RPT样板
            //GCN01602.PAYMENTS.20151014135500J6.QLPAY012R.5224.CSV-BANSTA.rpt
            // Rej3 样板
            //GCN01602.PAYMENTS.20151008020602.3802.winterPay0006.csv.rej3
            //GCNA5011.REPORTSCUST.20170402044147P6.QLPAY008R.5278.MT942-UTF8.rpt
            //GCNA6309.PAYMENTS.20191226100425XO.QLPAY020R.4877.INTRACUST.rpt

            // 加强型 GCN01201.20031703fr3024314700010007E.20200317080114.SWMT940-UTF8
            String[] filenames = fileName.split("\\.");

            //找出带日期的段历史余额文件存到前一天
            String datePath = "";

            if (filenames.length > 2) {
                datePath = filenames[2];
            } else {
                continue;
            }
            // filenames[3].contains("MT940") 针对加强型MT
            //  //GCNA6309.PAYMENTS.20191226100425XO.QLPAY020R.4877.INTRACUST.rpt
            if (filenames.length > 5 && (filenames[3].contains("MT940") || filenames[5].startsWith("INTRA") || filenames[5].startsWith("MT942") || filenames[5].startsWith("MT940") || filenames[5].startsWith("PRIORCUST"))) {
                Date fileRecDate = Format.Date8Format.parse(datePath.substring(0, 8));
                Calendar fileRecCal = Calendar.getInstance();
                fileRecCal.setTime(fileRecDate);
                // 把所有的历史或者今日都放到对应的日期文件夹下，历史的放在前一天的文件夹下（历史的文件第二天生成）。
                if (filenames[5].startsWith("PRIORCUST") || filenames[3].contains("MT940")) {
                    fileRecCal.add(Calendar.DAY_OF_MONTH, -1);
                }
                //fileRecCal.add(Calendar.DAY_OF_YEAR, -1);
                datePath = Format.Date8Format.format(fileRecCal.getTime());
            }

            //截取0-7 一共八位日期字段
            String toPath2 = getTrimPath(toPath) + File.separator + datePath.substring(0, 6) + File.separator + datePath.substring(6, 8);
            File toPaths = new File(toPath2);
            if (!toPaths.exists()) {
                toPaths.mkdirs();
            }
            //原文件路径
            String fullName = getTrimPath(fromPath) + File.separator + fileName;

            //拷贝文件 拷贝成功删除原文件
            if (copyFile(fullName, toPath2)) {
                WriteBankLogLn("拷贝文件" + fullName + "至" + toPath2);
                if (!new File(fullName).delete()) {
                    WriteBankLogLn("已备份文件" + fullName + " 删除失败,请手动删除");
                }
            }
        }
    }


    String getPaymentStatusResponseType(String path, String paymentFileName) {
        String paymentStatus = "";
        if (StringHelper.isNullOrEmpty(path) || StringHelper.isNullOrEmpty(paymentFileName)) {
            System.out.println("支付状态更新文件ACK3/REJ3路径为空!");
            return paymentStatus;
        }
        //判断文件夹是否存在
        if (!new File(path).exists()) {
            return paymentStatus;
        }
        //读取配置文件CSV文件导出的路径
        List<String> fileNames = getDirectoryAllFileName(path);
        for (String fileName : fileNames) {
            if (!fileName.contains(paymentFileName)) {
                continue;
            }
            //获取文件内容
            String content = FileHelper.readFileText(getTrimPath(path) + File.separator + fileName, getCharset());
            //支付状态更新文件数据分隔符(管道符号)
            String split = "\\|";
            String[] sArray = content.split(split);
            //<group id>.PAYMENTS.<yyyymmddhhmmssXX>.<filesize>.<filename>.rej1 or .rej2 or .rej3
            // e.g. GCNA5011.PAYMENTS.20141219093211L8.3690.test.txt.rej2
            // ACK3|21042008071836|GroupID.PAYMENTS.20080421031425.60843.Test.txt|08042115fp880000088170000
            //  |D0000345|H2H|75130|(INFO) File Sent|PAYSTS_XML
            //1、Response Type       返回类型 ack123/rej123
            //2、Date and Time       文件生成时间:ddMMyyyyHHmmss
            //3、File Name              文件名
            //4、UMI                       消息的Urid
            //5、Batch Number       批次号
            //6、Channel Indicator  文件传送渠道H2H
            //7、Error code              错误码
            //8、Response Message
            //9、Source/Product
            //匹配支付状态后删除此支付状态更新文件
            //System.IO.File.Delete(fullName);
            paymentStatus = sArray[0];
            break;
        }
        return paymentStatus;
    }

    String getPaymentStatusResponseTypeREJ3(String path, String paymentFileName, StringBuilder eorryCode, StringBuilder eorryMessage) {

        String paymentStatus = "";
        if (StringHelper.isNullOrEmpty(path) || StringHelper.isNullOrEmpty(paymentFileName)) {
            System.out.println("支付状态更新文件ACK3/REJ3路径为空!");
            return paymentStatus;
        }
        //判断文件夹是否存在
        if (!new File(path).exists()) {
            return paymentStatus;
        }
        //读取配置文件CSV文件导出的路径
        List<String> fileNames = getDirectoryAllFileName(path);
        for (String fileName : fileNames) {
            if (!fileName.contains(paymentFileName)) {
                continue;
            }
            String content = FileHelper.readFileText(getTrimPath(path) + File.separator + fileName, getCharset());
            //支付状态更新文件数据分隔符(管道符号)
            String split = "\\|";
            String[] sArray = content.split(split);
             /*  ACK3|21042008071836|GroupID.PAYMENTS.20080421031425.60843.Test.txt|08042115fp880000088170000
            |D0000345|H2H|75130|(INFO) File Sent|PAYSTS_XML
            */
            //1、Response Type       返回类型 ack123/rej123
            //2、Date and Time       文件生成时间:ddMMyyyyHHmmss
            //3、File Name              文件名
            //4、UMI                       消息的Urid
            //5、Batch Number       批次号
            //6、Channel Indicator  文件传送渠道H2H
            //7、Error code              错误码
            //8、Response Message
            //9、Source/Product
            //sArray[0] is Response Type、 sArray[2] is File Name
            if (sArray.length > 6) {
                paymentStatus = sArray[0];
                eorryCode.append(sArray[6]);
                eorryMessage.append(sArray[7]);
                break;
            }
        }

        return paymentStatus;
    }

    List<RetAtsBatPayRecDetail> paypoc(List<Date> dateBuffer, List<String> dtpostscripts) throws Exception {
        List<RetAtsBatPayRecDetail> detail1998s = new ArrayList<RetAtsBatPayRecDetail>();
        String sLine = "";
        for (Date datePathDate : dateBuffer) {
            String datePath = Format.Date8Format.format(datePathDate);
            //最�K�Y果RPT文件
            String rptPath = getH2HPath("PayReturnRPTbyWINTER");
            String toPath = getTrimPath(rptPath) + File.separator + datePath.substring(0, 6) + File.separator + datePath.substring(6, 8);
            //确认文件夹是存在的
            File toPathFile = new File(toPath);
            if (!toPathFile.exists()) {
                continue;
            }
            //获取路径下的所有文件名
            List<String> filenamelist = getDirChildNameByDate(toPath);
            if (filenamelist != null && filenamelist.size() > 0) {
                //第三层，文件夹下的文件列表
                for (String filename : filenamelist) {
                    //读取每一个文件
                    //文件路径
                    String fullName = getTrimPath(toPath) + File.separator + filename;
                    synchronized (this) {
                        //读取支付状态类型文件
                        //循环读取里面的内容，并且将内容进行查找，找到自己想要的那一笔数据。
                        InputStream inputStream = new FileInputStream(fullName);
                        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, getCharset()));
                        //"H","SCBLMYKXXXX","GROUPID1","161128","1229","28112016123535","Transaction Status Report","MY","","","","","","","","","","","","","","","",""
                        //"D","1500000143161000","F3","Accepted","D0000042","R0000064","20161128","20161124","",1400000.00,"MYR","MYR","MYR",0.000000,"","","","","500000000001","XXXXXXXXX TELCO INFRA XXX XXX","XXXXXXXXX TELCO INFRA XXX XXX","NO 00 XXXXX XXXXXXX XXX 0/0","XXXXXX BUSINESS PARK","/MALAYSIA","","","","","","012345678900","RTGS","","SCUISTS1R0000064","",""
                        // "D","1500000098161000","F2","Rejected","D0000070","R0000102","20161128","20161124","",20000.00,"MYR","MYR","MYR",0.000000,"","<88> Duplicate CR [1500000098161000]","","","200000000000002","XXXXXX XXXXXX XXX XXX-NEW4","XXXXXX XXXXXX XXX XXX-NEW4","00-00, 00 BUSINESS PARK 0","XXXXX XXXXXXX","/MALAYSIA","","","","","","012345678900","BT","","SCUISTS1R0000102","",""
                        // "D","1500000161161000","F3","Accepted","D0000067","R0000099","20161128","20161124","",3000.00,"MYR","MYR","MYR",0.000000,"","","","","100000000008","XXX SCIENCE AND TECHNOLOGIES CORP.","XXX SCIENCE AND TECHNOLOGIES CORP.","XXXXXXX XX XXXXXXX XXXXXXX CENTER 0","XXXXXXX DISTRICT","/CHINA","","","","","","012345678900","TT","","SCUISTS1R0000099","",""
                        // "T",3
                        while ((sLine = reader.readLine()) != null) {
                            Iterator<String> dtpostscript = dtpostscripts.iterator();
                            while (dtpostscript.hasNext()) {
                                String postscript = dtpostscript.next();
                                if (sLine.indexOf(postscript) >= 1) {
                                    WriteBankLogStep3(sLine);
                                    RetAtsBatPayRecDetail a = new RetAtsBatPayRecDetail();
                                    //D2 Customer reference 客户参考号
                                    String[] sLines = sLine.split(",");
                                    //把字符串的双引号都去掉
                                    a.payAct = sLines[29].replace("\"", "");
                                    a.recName = sLines[19].replace("\"", "");
                                    a.recAct = sLines[18].replace("\"", "");
                                    a.payAmount = sLines[9].replace("\"", "");
                                    a.curType = sLines[10].replace("\"", "");
                                    a.usage = sLines[28].replace("\"", "");
                                    a.postScript = postscript;
                                    a.memo = sLines[0].replace("\"", "");
                                    a.payInfoCode = sLines[15].replace("\"", "");
                                    a.result = sLines[2].replace("\"", "").trim();
                                    detail1998s.add(a);
                                    dtpostscript.remove();
                                }
                                if (dtpostscripts.size() == 0) {
                                    break;
                                }
                            }
                            if (dtpostscripts.size() == 0) {
                                break;
                            }
                        }
                        reader.close();
                        inputStream.close();
                    }
                    if (dtpostscripts.size() == 0) {
                        break;
                    }
                }
            } else {
                continue;//如果没有文件，那么继续检索下一个文件夹、
            }
            if (dtpostscripts.size() == 0) {
                break;
            }
        }
        return detail1998s;
    }

    //代收查�，需修改
    List<RetAtsBatPayRecDetail> recpoc(List<Date> dateBuffer, String respType, List<Map<String, Object>> dtpostscript) throws Exception {

        List<RetAtsBatPayRecDetail> detail9198s = new ArrayList<RetAtsBatPayRecDetail>();
        String sLine;

        for (Date datePathDate : dateBuffer) {

            String datePath = Format.Date8Format.format(datePathDate);

            //最�K�Y果RPT文件
            String rptPath = getH2HPath("RecReturnRPTbyWINTER");

            String toPath = getTrimPath(rptPath) + File.separator + datePath.substring(0, 6) + File.separator + datePath.substring(6, 8);

            if (StringHelper.isNullOrEmpty(toPath)) {
                WriteBankLogLn("支付状态文件路径为空!");
            }
            //确认文件夹是存在的
            if (!new File(toPath).exists()) {
                continue;
            }

            List<String> filenamelist = getDirectoryAllFileName(toPath);
            if (filenamelist != null && filenamelist.size() > 0) {
                //第三层，文件夹下的文件列表
                for (String filename : filenamelist) {
                    //读取每一个文件
                    //文件路径
                    String fullName = getTrimPath(toPath) + File.separator + filename;
                    synchronized (this) {
                        //读取支付状态类型文件
                        //循环读取里面的内容，并且将内容进行查找，找到自己想要的那一笔数据。
                        InputStream inputStream = new FileInputStream(fullName);
                        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, getCharset()));
                        while ((sLine = reader.readLine()) != null) {
                            if (!"".equals(sLine)) {
                                for (Map<String, Object> dr : dtpostscript) {
                                    String postscript = dr.get("POSTSCRIPT").toString();
                                    if (sLine.indexOf(postscript) >= 1) {
                                        WriteBankLogLn("银行返回报文为" + sLine);
                                        RetAtsBatPayRecDetail a = new RetAtsBatPayRecDetail();
                                        // String[] sLines = sLine.split(",");
                                        //这里特殊处理一下，有些金额会在中间添加逗号，那么需要将金额中的逗号去掉在做处理，否则会出现字段错位的问题
                                        String[] sLines = sLine.split("\"");
                                        if (sLines.length == 3) {
                                            //去掉逗号
                                            String sLinesOne = sLines[1].replace(",", "");
                                            sLine = sLines[0] + sLinesOne + sLines[2];
                                        }

                                        sLines = sLine.split(",");
                                        //把字符串的双引号都去掉
                                        //----------------------------------------------------
                                        a.recAct = sLines[0].replace("\"", "");
                                        a.payName = sLines[9].replace("\"", "");
                                        a.payAct = sLines[10].replace("\"", "");
                                        a.payAmount = sLines[6].replace("\"", "").trim();
                                        //币种要转化一下
                                        a.curType = sLines[3].replace("\"", "");
                                        if ("Yuan Renminbi".equals(a.curType)) {
                                            a.curType = "CNY";
                                        }
                                        a.usage = sLines[21].replace("\"", "");
                                        a.result = sLines[19].replace("\"", "").trim();
                                        if ("Success".equals(a.result)) {
                                            a.payInfoCode = "成功";
                                        } else {
                                            a.payInfoCode = sLines[20].replace("\"", "");
                                        }
                                        a.memo = sLines[21].replace("\"", "");
                                        //   detail9198s.Add(postscript, a);
                                        detail9198s.add(a);
                                    }
                                    if (dtpostscript.size() == detail9198s.size()) {
                                        break;
                                    }
                                }
                            }
                            if (dtpostscript.size() == detail9198s.size()) {
                                break;
                            }
                        }
                        reader.close();
                        inputStream.close();
                    }
                    if (dtpostscript.size() == detail9198s.size()) {
                        break;
                    }
                }
            } else {
                continue;//如果没有文件，那么继续检索下一个文件夹、
            }
            if (dtpostscript.size() == detail9198s.size()) {
                break;
            }
        }
        return detail9198s;
    }

    /**
     * 获取H2H文件路径保存目录
     *
     * @param dirPath
     * @return
     */
    String getH2HPath(String dirPath) throws Exception {
        return getBankConfig().getMapValueByKey("fileUrl", dirPath);
    }

    /**
     * 路径保证末尾带 \
     *
     * @param p_path
     * @return
     */
    String getTrimPath(String p_path) {
        return StringHelper.trimEnd(p_path, File.separator);
    }

    String convertCommaToPoint(String amount) {
        if (!StringUtils.isEmpty(amount)) {
            if (amount.indexOf('.') > -1) {
                //Do nothing
            } else if (amount.indexOf(',') > -1) {
                if (amount.indexOf(',') - amount.lastIndexOf(',') == 0) {
                    amount = amount.replace(',', '.');
                }
            }
        }
        return amount;
    }

    void getMsgBody(ReqPayRecDetail detail, StringBuilder msgBody, List<String> askNumMap, String isPaySpd, String commandCode) throws Exception {
        //注释，组装字段名称
        //1、Record Type	1，记录类型
        //2、Payment Type	2，付款方式
        //3、Processing Mode	3，加工方式
        //4、Service Type	4、服务类型
        //5、Customer Reference	5，客户咨询
        //6、Customer Memo	6，客户备忘录
        //7、Debit A/C Country Code	7、借记/ c++的国家代码
        //8、Debit A/C City Code	8、借记/ c++代码
        //9、Debit A/C No.	9、借记卡/ c++号
        //10、Payment/Value Date	10、付款/日期
        //11、Payee/Beneficiary Name : BO*	11、收款人/受益人的名字在博*
        //12、Payee Address1 : BO*	12、收款人地址1博*
        //13、Payee Address2 : BO*	13、收款人演说2博*
        //14、Payee Country Code	14、收款人的国家代码
        //15、Payee Fax Number*	15、收款传真号码
        //16、Payee/Beneficiary Bank Code*	16、收款人/受益人银行代码
        //17、Payee/Beneficiary bank local clearing code*	17、收款人/受益人银行当地清算代码*
        //18、Beneficiary local clearing Branch Code	18、受益人当地结算部门代码
        //19、Beneficiary branch sub-code	19，受益分支代码
        //20、Beneficiary A/C No.	20、受益人一、丙号
        //21、Payment Details 1 : BO	21，付款详情1在渤
        //22、Payment Details 2 : BO	22，付款详情2在渤
        //23、VAT Amount	23，增值税
        //24、WHT Printing Location	24、WHT印刷位置
        //25、WHT Form ID	25、WHT表ID
        //26、WHT Tax ID	26、WHT税号
        //27、WHT Ref. No.	27、WHT编号
        //28、WHT Type 1	28、WHT型1
        //29、WHT Description 1	29、WHT描述1
        //30、WHT Gross Amount 1	30、WHT总金额的1
        //31、WHT Amount 1	31、WHT金额1
        //32、WHT Type 2	32、WHT型2
        //33、WHT Description 2	33、WHT描述2
        //34、WHT Gross Amount 2	34、WHT总金额的2
        //35、WHT Amount 2	35、WHT金额2
        //36、Discount Amount	36，折扣金额
        //37、Invoice Format	37、发票格式
        //38、Payment Currency	38，支付货币
        //39、Invoice/Payment Amount	39、发票/付款金额
        //40、Local Charge To	40本地费用
        //41、Overseas Charge To	41，海外收费
        //42、Intermediary Bank Code	42，中介银行代码
        String strPayment = "";
        //请求详情
        //一共63个  最后个D 为了splite出所有中间的空字符
        //代发工资拼装
        if (commandCode != null && commandCode.equals("198802")) {
            strPayment = "P,PAY,BA,,,,CN,SHA,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,E";
        } else {
            //198802-190802RGTS模板   198801ACH模板
            if ("1".equals(detail.sameBnk)) {
                //同行走BT
                strPayment = "P,BT,ON,,,,CN,SHA,,,,,,,,SCBLCNSXSHA,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,E";
            } else {
                //金额大于5万 或加急 走RTGS---->不论大小额。只要求加急  走RTGS
                if ("1".equals(isPaySpd)) {
                    strPayment = "P,RTGS,ON,,,,CN,SHA,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,E";
                } else {
                    strPayment = "P,ACH,BA,,,,CN,SHA,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,E";
                }
            }
        }

        String[] sPaymentItems = strPayment.split(",");
        //支付对账码
        sPaymentItems[4] = detail.askNumber;
        //备注-->不支持中文
        if (detail.memo != null && !pattern.matcher(detail.memo).find()) {
            sPaymentItems[5] = hasCommaAddDoubleQuotes(detail.memo);
        }
        //付款账户
        sPaymentItems[8] = detail.payAct;
        //PayDate
        Date payDate = Format.Date10Format.parse(detail.payDate);
        sPaymentItems[9] = sdf.format(payDate);
        //收款人姓名sPaymentItems[10]  如果有中文需要Base64放到50,51

        if ("BT".equals(sPaymentItems[1])) {
            String enName = getBankConfig().getMapValueByKey("BTnameMapping", detail.recAct);
            if (enName != null && !"".equals(enName)) {
                detail.recName = getBankConfig().getMapValueByKey("BTnameMapping", detail.recAct);
            }
        }

        recNameFormat(sPaymentItems, detail.recName);

        if (!"BT".equals(sPaymentItems[1])) {
            //收款人银行Code RTGS/ACH forcnaps Code长度小于11
            sPaymentItems[15] = detail.cnapsCode.length() > 11 ? detail.cnapsCode.substring(0, 11) : detail.cnapsCode;
        }
        //收款人账号
        sPaymentItems[19] = detail.recAct;
        //Invoice Format  2 or 4 columns of invoice details

        //付款币种
        sPaymentItems[37] = convertCurToBank(detail.payCur);
        //付款金额 Invoice Amount  (9(12).9(2))
        sPaymentItems[38] = hasCommaAddDoubleQuotes(detail.payAmount);
        //收款银行名称
        //sPaymentItems[55] = detail.recBankName;

        //收款银行名称 sPaymentItems[55]
        recBnkNmFormat(sPaymentItems, detail.cnapsName);
        String memo = "+" + detail.abstractATS + "+" + detail.purpose;
        //57要求转换成BASE64   长度小于70  sPaymentItems[56]
        memoFormat(sPaymentItems, memo);

        StringBuilder strLine = new StringBuilder();
        for (String strTemp : sPaymentItems) {
            strLine.append(strTemp).append(",");
        }
        //删除最后额外的三个字符 (,E , )
        strLine.delete(strLine.length() - 3, strLine.length());
        strLine.append("\r\n");
        msgBody.append(strLine.toString());
        // 特殊加工，将数据装入批次号流水号映射
        askNumMap.add(sPaymentItems[4]);
    }

    void recBnkNmFormat(String[] sPaymentItems, String cnapsName) {
        String finalMemo = Base64Helper.getBase64(cnapsName, "GBK");
        if (finalMemo.length() <= 70) {
            sPaymentItems[55] = finalMemo;
        } else {
            int cutPoint = 26;
            while (Base64Helper.getBase64(cnapsName.substring(0, cutPoint), "GBK").length() <= 70) {
                cutPoint++;
            }
            cutPoint--;
            sPaymentItems[55] = Base64Helper.getBase64(cnapsName.substring(cutPoint), "GBK");
        }
    }

    String getMsgBody(ReqBatPayRec p_req1988, List<String> askNumMap) throws Exception {
        StringBuilder sbPaymentBody = new StringBuilder();
        while (p_req1988.readRecord()) {
            getMsgBody(p_req1988.readedDetail, sbPaymentBody, askNumMap, p_req1988.paySpd, p_req1988.reqHeader.commandCode);
        }
        return sbPaymentBody.toString();
    }

    void recNameFormat(String[] sPaymentItems, String recName) {
        //收款人姓名  如果有中文需要Base64放到50,51
        if (recName != null && !"".equals(recName)) {
            Matcher matcher = pattern.matcher(recName);
            if (!matcher.find()) {
                if (recName.length() > 70) {
                    sPaymentItems[10] = recName.substring(0, 35);
                    sPaymentItems[11] = recName.substring(35, 70);
                    sPaymentItems[50] = Base64Helper.getBase64(sPaymentItems[11], "GBK");
                } else if (recName.length() > 35) {
                    sPaymentItems[10] = recName.substring(0, 35);
                    sPaymentItems[11] = recName.substring(35);
                    sPaymentItems[50] = Base64Helper.getBase64(sPaymentItems[11], "GBK");
                } else {
                    sPaymentItems[10] = recName;
                }
                //如果字符串包含中文，那么将10（英文收款名称）换成".",将中文名字放入49，当49太长的时候，剩下的放入50
            } else {
                sPaymentItems[10] = ".";
                sPaymentItems[49] = Base64Helper.getBase64(recName, "GBK");
                if (sPaymentItems[49].length() > 80) {
                    int cutPoint1 = 15;
                    int cutPoint2 = 30;
                    while (Base64Helper.getBase64(recName.substring(0, cutPoint1), "GBK").length() <= 40) {
                        cutPoint1++;
                    }
                    cutPoint1--;
                    try {
                        while (Base64Helper.getBase64(recName.substring(cutPoint1, cutPoint2), "GBK").length() <= 40) {
                            cutPoint2++;
                        }
                    } catch (Exception ignored) {
                    } finally {
                        cutPoint2--;
                    }
                    sPaymentItems[49] = Base64Helper.getBase64(recName.substring(0, cutPoint1), "GBK");
                    sPaymentItems[50] = Base64Helper.getBase64(recName.substring(cutPoint1, cutPoint2), "GBK");
                } else if (sPaymentItems[49].length() > 40) {
                    int cutPoint1 = 15;
                    while (Base64Helper.getBase64(recName.substring(0, cutPoint1), "GBK").length() <= 40) {
                        cutPoint1++;
                    }
                    cutPoint1--;
                    sPaymentItems[49] = Base64Helper.getBase64(recName.substring(0, cutPoint1), "GBK");
                    sPaymentItems[50] = Base64Helper.getBase64(recName.substring(cutPoint1), "GBK");
                }
            }
        }
    }

    void memoFormat(String[] sPaymentItems, String memo) {
        String finalMemo = Base64Helper.getBase64(memo, "GBK");
        if (finalMemo.length() <= 70) {
            sPaymentItems[56] = finalMemo;
        } else {
            int cutPoint = 26;
            while (Base64Helper.getBase64(memo.substring(0, cutPoint), "GBK").length() <= 70) {
                cutPoint++;
            }
            cutPoint--;
            sPaymentItems[56] = Base64Helper.getBase64(memo.substring(cutPoint), "GBK");
        }
    }

    // 复制文件
    public static void cFile(File sourceFile, File targetFile) throws IOException {
        // 新建文件输入流并对它进行缓冲
        FileInputStream input = new FileInputStream(sourceFile);
        BufferedInputStream inBuff = new BufferedInputStream(input);
        // 新建文件输出流并对它进行缓冲
        FileOutputStream output = new FileOutputStream(targetFile);
        BufferedOutputStream outBuff = new BufferedOutputStream(output);
        // 缓冲数组
        byte[] b = new byte[1024 * 5];
        int len;
        while ((len = inBuff.read(b)) != -1) {
            outBuff.write(b, 0, len);
        }
        // 刷新此缓冲的输出流
        outBuff.flush();
        //关闭流
        inBuff.close();
        outBuff.close();
        output.close();
        input.close();
    }

    // 复制文件夹
    public static void copyDirectiory(String sourceDir, String targetDir) throws IOException {
        // 新建目标目录
        (new File(targetDir)).mkdirs();
        // 获取源文件夹当前下的文件或目录
        File[] file = (new File(sourceDir)).listFiles();
        for (int i = 0; i < file.length; i++) {
            if (file[i].isFile()) {
                // 源文件
                File sourceFile = file[i];
                // 目标文件
                File targetFile = new File(new File(targetDir).getAbsolutePath() + File.separator + file[i].getName());
                cFile(sourceFile, targetFile);
            }
            if (file[i].isDirectory()) {
                // 准备复制的源文件夹
                String dir1 = sourceDir + "/" + file[i].getName();
                // 准备复制的目标文件夹
                String dir2 = targetDir + "/" + file[i].getName();
                copyDirectiory(dir1, dir2);
            }
        }
    }

    /***
     * 删除文件夹
     *
     *  folderPath文件夹完整绝对路径
     */
    public static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); // 删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            java.io.File myFilePath = new java.io.File(filePath);
            myFilePath.delete(); // 删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     * 删除指定文件夹下所有文件
     *
     * @param path 文件夹完整绝对路径
     * @return
     */
    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);// 再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }


    public static boolean deleteFile(File file) {

        // 路径为文件且不为空则进行删除

        boolean flag = false;
        if (file.isFile() && file.exists()) {
            System.gc();    //加上确保文件能删除，不然可能删不掉

            flag = file.delete();

        }
        return flag;
    }

}
